package online.heycm.platform.common.entity.exception;

import online.heycm.platform.common.entity.result.ErrorCode;
import online.heycm.platform.common.entity.result.Optional;
import online.heycm.platform.common.entity.result.Result;
import org.apache.commons.lang3.StringUtils;

/**
 * 断言
 *
 * @author heycm
 * @since 2023/12/1 20:29
 */
public class Assert {

    private Assert() {}

    public static void require(Optional<?> optional) {
        if (optional.fail()) {
            BizException.biz(optional.error());
        }
    }

    public static void require(Result<?> result) {
        if (!result.ok()) {
            BizException.biz(result.getCode(), result.getMessage());
        }
    }

    public static void isTrue(boolean expression, String message) {
        if (!expression) {
            BizException.biz(message);
        }
    }

    public static void isTrue(boolean expression, ErrorCode errorCode) {
        if (!expression) {
            BizException.biz(errorCode);
        }
    }

    public static void isTrue(boolean expression, int code, String message) {
        if (!expression) {
            BizException.biz(code, message);
        }
    }

    public static void isTrue(boolean expression, RuntimeException e) {
        if (!expression) {
            throw e;
        }
    }

    public static void notNull(Object object, String message) {
        if (null == object) {
            BizException.biz(message);
        }
    }

    public static void notNull(Object object, ErrorCode errorCode) {
        if (null == object) {
            BizException.biz(errorCode);
        }
    }

    public static void notNull(Object object, int code, String message) {
        if (null == object) {
            BizException.biz(code, message);
        }
    }

    public static void hasText(String string, String message) {
        if (StringUtils.isBlank(string)) {
            BizException.biz(message);
        }
    }

    public static void hasText(String string, ErrorCode errorCode) {
        if (StringUtils.isBlank(string)) {
            BizException.biz(errorCode);
        }
    }

    public static void hasText(String string, int code, String message) {
        if (StringUtils.isBlank(string)) {
            BizException.biz(code, message);
        }
    }
}
